/**
 * 高德地图工具
 */
export class AMapUtil {
  constructor(apiKey) {
    this.apiKey = apiKey
    this.map = null
    this.markers = []
    this.polyline = null
  }

  /**
   * 初始化地图
   * @param {string} containerId - 地图容器ID
   * @param {Object} options - 地图配置
   */
  initMap(containerId, options = {}) {
    return new Promise((resolve, reject) => {
      // 检查容器是否存在
      const container = document.getElementById(containerId)
      if (!container) {
        reject(new Error(`地图容器 ${containerId} 不存在`))
        return
      }

      // 如果API已加载，直接创建地图
      if (typeof AMap !== 'undefined') {
        this._createMap(containerId, options, resolve, reject)
        return
      }

      // 动态加载高德地图API
      if (!this.apiKey || this.apiKey === 'your_amap_api_key') {
        reject(new Error('高德地图API Key未配置，请在.env文件中设置VUE_APP_AMAP_KEY'))
        return
      }

      // 检查是否已经在加载
      if (window._amapLoading) {
        // 等待加载完成
        const checkInterval = setInterval(() => {
          if (typeof AMap !== 'undefined') {
            clearInterval(checkInterval)
            this._createMap(containerId, options, resolve, reject)
          }
        }, 100)
        return
      }

      window._amapLoading = true
      const callbackName = `initAMap_${Date.now()}`
      
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = `https://webapi.amap.com/maps?v=2.0&key=${this.apiKey}&callback=${callbackName}`
      
      script.onerror = () => {
        window._amapLoading = false
        reject(new Error('高德地图API加载失败，请检查API Key和网络连接'))
      }
      
      window[callbackName] = () => {
        window._amapLoading = false
        delete window[callbackName]
        // 等待一小段时间确保AMap对象完全初始化
        setTimeout(() => {
          this._createMap(containerId, options, resolve, reject)
        }, 100)
      }
      
      document.head.appendChild(script)
    })
  }

  _createMap(containerId, options, resolve, reject) {
    // 重试机制：最多重试3次
    let containerRetryCount = 0
    let amapRetryCount = 0
    const maxRetries = 3

    const tryCreateMap = () => {
      try {
        // 再次检查容器是否存在（带重试）
        let container = document.getElementById(containerId)
        if (!container) {
          if (containerRetryCount < maxRetries) {
            containerRetryCount++
            setTimeout(tryCreateMap, 200)
            return
          }
          reject(new Error(`地图容器 ${containerId} 不存在，请确保DOM已渲染`))
          return
        }

        // 检查AMap是否已加载
        if (typeof AMap === 'undefined') {
          if (amapRetryCount < maxRetries) {
            amapRetryCount++
            setTimeout(tryCreateMap, 200)
            return
          }
          reject(new Error('高德地图API未加载，请检查API Key和网络连接'))
          return
        }

        const defaultOptions = {
          zoom: 12,
          center: [115.89, 28.68], // 南昌市中心坐标
          viewMode: '3D', // 3D视图
          ...options
        }

        // 销毁旧地图实例（如果存在）
        if (this.map) {
          try {
            // 清除标记和路线
            this.clearMarkers()
            this.clearRoute()
            this.map.destroy()
          } catch (e) {
            console.warn('销毁旧地图实例失败:', e)
          }
        }

        this.map = new AMap.Map(containerId, defaultOptions)
        
        // 监听地图加载完成事件
        let resolved = false
        const completeHandler = () => {
          if (!resolved) {
            resolved = true
            resolve(this.map)
          }
        }

        this.map.on('complete', completeHandler)

        // 设置超时，防止complete事件未触发
        setTimeout(() => {
          if (!resolved && this.map) {
            // 检查地图状态
            if (this.map.getStatus && this.map.getStatus() === 'complete') {
              completeHandler()
            } else {
              // 即使状态不是complete，也resolve（地图可能已经可用）
              completeHandler()
            }
          }
        }, 3000)
      } catch (error) {
        // 如果是容器或AMap未加载的错误，不重试
        if (error.message && (
          error.message.includes('容器') || 
          error.message.includes('API未加载')
        )) {
          reject(error)
        } else {
          // 其他错误，尝试重试
          const totalRetries = containerRetryCount + amapRetryCount
          if (totalRetries < maxRetries * 2) {
            setTimeout(tryCreateMap, 200)
          } else {
            reject(error)
          }
        }
      }
    }

    tryCreateMap()
  }

  /**
   * 创建标记图标（使用Canvas，避免btoa编码问题）
   * @param {string} color - 颜色
   * @param {string} text - 文本
   * @param {number} size - 大小
   */
  _createMarkerIcon(color, text, size = 32) {
    try {
      const canvas = document.createElement('canvas')
      canvas.width = size
      canvas.height = size
      const ctx = canvas.getContext('2d')

      // 绘制圆形背景
      ctx.beginPath()
      ctx.arc(size / 2, size / 2, size / 2 - 2, 0, Math.PI * 2)
      ctx.fillStyle = color
      ctx.fill()
      ctx.strokeStyle = 'white'
      ctx.lineWidth = 2
      ctx.stroke()

      // 绘制文本
      if (text) {
        ctx.fillStyle = 'white'
        ctx.font = `bold ${text === '起' ? 14 : 12}px Arial`
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        ctx.fillText(text, size / 2, size / 2)
      } else {
        // 绘制小圆点
        ctx.beginPath()
        ctx.arc(size / 2, size / 2, size / 6, 0, Math.PI * 2)
        ctx.fillStyle = 'white'
        ctx.fill()
      }

      const iconUrl = canvas.toDataURL('image/png')

      return new AMap.Icon({
        size: new AMap.Size(size, size),
        image: iconUrl,
        imageOffset: new AMap.Pixel(-size / 2, -size),
        imageSize: new AMap.Size(size, size)
      })
    } catch (error) {
      console.warn('创建图标失败:', error)
      return null
    }
  }

  addMarkers(positions) {
    // 先清除旧标记
    this.clearMarkers()

    // 确保地图已加载
    if (!this.map) {
      console.warn('地图未初始化，无法添加标记')
      return
    }

    positions.forEach((pos, index) => {
      // 根据是否为起点设置不同的图标
      const isStart = pos.isStart || index === 0
      
      // 创建自定义图标（使用Canvas避免btoa编码问题）
      let icon = null
      try {
        if (positions.length === 1) {
          // 单个标记：红色圆点
          icon = this._createMarkerIcon('#F56C6C', '', 32)
        } else {
          if (isStart) {
            // 起点：绿色"起"
            icon = this._createMarkerIcon('#67c23a', '起', 32)
          } else {
            // 途经点：蓝色数字
            icon = this._createMarkerIcon('#409eff', String(index), 32)
          }
        }
      } catch (error) {
        console.warn('创建自定义图标失败，使用默认图标:', error)
        icon = null
      }

      const marker = new AMap.Marker({
        position: [pos.lng, pos.lat],
        title: pos.title || `景点${index + 1}`,
        icon: icon || undefined, // 如果自定义图标失败，使用默认图标
        label: {
          content: `<div style="background: rgba(255,255,255,0.9); padding: 2px 6px; border-radius: 4px; font-size: 12px; color: #606266; border: 1px solid rgba(200,16,46,0.2); white-space: nowrap;">${pos.title || `景点${index + 1}`}</div>`,
          direction: 'right',
          offset: new AMap.Pixel(20, -10)
        },
        zIndex: isStart ? 100 : 50,
        visible: true,
        clickable: true
      })

      // 如果有详细信息，创建信息窗口
      if (pos.info) {
        const infoWindow = new AMap.InfoWindow({
          content: pos.info,
          offset: new AMap.Pixel(0, -30),
          closeWhenClickMap: true,
          isCustom: false
        })

        marker.on('click', () => {
          infoWindow.open(this.map, marker.getPosition())
        })

        // 保存信息窗口引用
        marker.infoWindow = infoWindow
      }

      this.markers.push(marker)
      this.map.add(marker)
    })

    // 等待地图完全加载后再调整视野
    if (this.markers.length > 0) {
      // 如果地图已加载完成，立即调整视野
      if (this.map && this.map.getStatus && this.map.getStatus() === 'complete') {
        setTimeout(() => {
          this.map.setFitView(this.markers, false, [50, 50, 50, 50])
        }, 100)
      } else {
        // 等待地图加载完成
        this.map.on('complete', () => {
          setTimeout(() => {
            if (this.markers.length > 0) {
              this.map.setFitView(this.markers, false, [50, 50, 50, 50])
            }
          }, 100)
        })
      }
    }
  }

  /**
   * 绘制路线
   * @param {Array} path - 路线坐标数组 [[lng, lat], ...]
   */
  drawRoute(path) {
    if (this.polyline) {
      this.map.remove(this.polyline)
    }

    this.polyline = new AMap.Polyline({
      path: path,
      isOutline: true,
      outlineColor: '#ffeeff',
      borderWeight: 3,
      strokeColor: '#3366FF',
      strokeOpacity: 1,
      strokeWeight: 6,
      lineJoin: 'round',
      lineCap: 'round',
      zIndex: 50
    })

    this.map.add(this.polyline)
    this.map.setFitView([this.polyline])
  }

  /**
   * 清除所有标记
   */
  clearMarkers() {
    this.markers.forEach(marker => {
      // 关闭信息窗口
      if (marker.infoWindow) {
        marker.infoWindow.close()
      }
      if (this.map) {
        this.map.remove(marker)
      }
    })
    this.markers = []
  }

  /**
   * 清除路线
   */
  clearRoute() {
    if (this.polyline) {
      this.map.remove(this.polyline)
      this.polyline = null
    }
  }

  /**
   * 销毁地图
   */
  destroy() {
    if (this.map) {
      this.map.destroy()
      this.map = null
    }
    this.markers = []
    this.polyline = null
  }
}

